package com.springboot.java;

import com.google.common.collect.Ordering;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: TongRui乀
 * @Date: 2020-03-08 11:41
 * @description： 如何证明ArrayList是有序的
 */
@Slf4j
public class IsArrayListSorted {


    /**
     * 遍历集合判断 compareTo 返回值是否都是一致的
     *
     * @return
     */
    public static boolean isSorted_01(List<String> sortedList) {

        if (sortedList != null && sortedList.size() == 1) {
            return true;
        }

        Iterator<String> iterator = sortedList.iterator();

        // 获取集合中的第一个元素
        String previous = iterator.next();

        while (iterator.hasNext()) {

            String current = iterator.next();

            // 判断compareTo的值是否都是大于0的
            if (previous.compareTo(current) > 0) {
                return false;
            }
            // 继续下一次
            previous = current;
        }
        return true;
    }



    public static boolean isSorted(List<String> listOfStrings) {
        return isSorted(listOfStrings, listOfStrings.size());
    }

    public static boolean isSorted(List<String> listOfStrings, int index) {
        if (index < 2) {
            return true;
        } else if (listOfStrings.get(index - 2).compareTo(listOfStrings.get(index - 1)) > 0) {
            return false;
        } else {
            return isSorted(listOfStrings, index - 1);
        }
    }

    public static boolean isSortedGuava(List<String> listOfStrings){


        return Ordering.natural().isOrdered(listOfStrings);
    }

    public static void main(String[] args) {

        List<String> strings = Arrays.asList("bb", "aa", "cc");

        log.info("{}", isSorted_01(strings));

        log.info("{}", isSorted(strings));

        log.info("{}", isSortedGuava(strings));
    }
}
